package org.example.filters;

import ch.qos.logback.classic.spi.EventArgUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("Auth 前置服务");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst("token");
        System.out.println("Auth过滤器接到的token为"+token);
        if (StringUtils.isEmpty(token)){
            HashMap hashMap = new HashMap() {{
                put("msg", "token为空");
            }};
            return response(response,hashMap);
        }else {
            if (!"123".equals(token)){
                HashMap hashMap = new HashMap() {{
                    put("msg", "token无效");
                }};
                return response(response,hashMap);
            }else {
                return chain.filter(exchange);
            }

        }

    }

    private Mono<Void> response(ServerHttpResponse response, HashMap hashMap) {
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        String jsonStr = JSONUtil.toJsonStr(hashMap);
        DataBuffer wrap = response.bufferFactory().wrap(jsonStr.getBytes());
        // 响应返回结果，
        return response.writeWith(Flux.just(wrap));
    }


    /**
     * 值越小，越先执行
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
